home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 1.toast / What's New? / Sample Code / QuickTime / Wired Movies and Sprites / DesktopSprites / ImageCompressionUtilities.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-06  |  28.2 KB  |  867 lines  |  [TEXT/CWIE]

  1. /*
  2.     File:        ImageCompressionUtilities.c
  3.     
  4.     Description: Image Compression Utilities
  5.  
  6.     Author:        Peter Hoddie, Sean Allen, Chris Flick
  7.     Revised by:          Tim Monroe
  8.  
  9.     Copyright:     © Copyright 1999 Apple Computer, Inc. All rights reserved.
  10.     
  11.     Disclaimer:    IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
  12.                 ("Apple") in consideration of your agreement to the following terms, and your
  13.                 use, installation, modification or redistribution of this Apple software
  14.                 constitutes acceptance of these terms.  If you do not agree with these terms,
  15.                 please do not use, install, modify or redistribute this Apple software.
  16.  
  17.                 In consideration of your agreement to abide by the following terms, and subject
  18.                 to these terms, Apple grants you a personal, non-exclusive license, under Apple’s
  19.                 copyrights in this original Apple software (the "Apple Software"), to use,
  20.                 reproduce, modify and redistribute the Apple Software, with or without
  21.                 modifications, in source and/or binary forms; provided that if you redistribute
  22.                 the Apple Software in its entirety and without modifications, you must retain
  23.                 this notice and the following text and disclaimers in all such redistributions of
  24.                 the Apple Software.  Neither the name, trademarks, service marks or logos of
  25.                 Apple Computer, Inc. may be used to endorse or promote products derived from the
  26.                 Apple Software without specific prior written permission from Apple.  Except as
  27.                 expressly stated in this notice, no other rights or licenses, express or implied,
  28.                 are granted by Apple herein, including but not limited to any patent rights that
  29.                 may be infringed by your derivative works or by other works in which the Apple
  30.                 Software may be incorporated.
  31.  
  32.                 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
  33.                 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
  34.                 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  35.                 PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
  36.                 COMBINATION WITH YOUR PRODUCTS.
  37.  
  38.                 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
  39.                 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  40.                 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  41.                 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
  42.                 OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
  43.                 (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
  44.                 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45.                 
  46.     Change History (most recent first):
  47.  
  48.        <5>         08/30/00    srk        Carbonization
  49.        <4>         12/16/98    rtm        removed orphaned prototype for compressTransparentRLEwithHitTesting
  50.        <3>         05/28/98    rtm        added some typecasting to minimize MSDev compiler warnings
  51.        <2>         03/22/98    rtm        made changes to RecompressPictureFileWithTransparency, as per Chris' fixes
  52.        <1>         03/27/98    rtm        existing file
  53.  
  54. */
  55.  
  56.  
  57. /************************************************************
  58. *                                                                                                                                           *
  59. *    INCLUDE FILES                                                                                                              *
  60. *                                                                                                                                           *
  61. *************************************************************/
  62.  
  63.  
  64. #ifndef _IMAGECOMPRESSIONUTILITIES_
  65. #include "ImageCompressionUtilities.h"
  66.  
  67.  
  68. /************************************************************
  69. *                                                                                                                                           *
  70. *    PROTOTYPES                                                                                                                  *
  71. *                                                                                                                                           *
  72. *************************************************************/
  73.  
  74.  
  75. static pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags );
  76. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap );
  77. static void DrawPictureNoDither(PicHandle pic, const Rect *bounds);
  78. static OSErr prepareFor16BitCompress(PicHandle *pic);
  79. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  80.  
  81. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType portType, void * refcon );
  82.  
  83.  
  84. /************************************************************
  85. *                                                                                                                                           *
  86. *    CONSTANTS                                                                                                                    *
  87. *                                                                                                                                           *
  88. *************************************************************/
  89.  
  90.  
  91. // We use the Animation compressor at 16 bit depth in these utilities
  92. #define kCompressDepth    16
  93.  
  94. // A few macros to help with error handling
  95.  
  96. #define        BailIf(a, e)         {if (a)     { err = e; goto bail; }}
  97.  
  98. #define        BailOSErr(a)         {if ((err = a) != noErr)    goto bail;}
  99.  
  100. #define        BailMemErr(a)        {a; if ((err = MemError()) != noErr) goto bail;}
  101.  
  102.  
  103.  
  104. /************************************************************
  105. *                                                                                                                                           *
  106. *    STRUCTURES                                                                                                                  *
  107. *                                                                                                                                           *
  108. *************************************************************/
  109.  
  110.  
  111.  
  112. // Used for compressing QuickDraw pictures with transparency/hittesting
  113.  
  114. typedef struct {
  115.     PicHandle    picture;
  116. } PictureCompressProcData;
  117.  
  118.  
  119. // Used for recompressing QuickTime compressed data with transparency/hittesting
  120.  
  121. typedef struct {
  122.     ImageDescriptionHandle    imageDesc;
  123.     Handle                    imageData;
  124. } CompressedImageCompressProcData;
  125.  
  126.  
  127. typedef struct {
  128.     CGrafPtr tempPort;
  129.     Handle data;
  130.     ImageDescriptionHandle idh;
  131. } extractPictRecord;
  132.  
  133.  
  134. // PICT to compressed image conversion
  135.  
  136. //    Given a QuickDraw picture, extract QuickTime compressed image data and description, if any.
  137. //
  138. //    It does this by creating a temporary CGrafPort, installing a QuickDraw bottleneck
  139. //    routine for the StdPix call, and then drawing the picture. Since this routine will
  140. //    be called whenever QuickTime compressed image data is encountered, it can
  141. //    stash away any found compressed data and description. On DrawPicture's return, the
  142. //    stashed data and description is retrieved and returned to the caller.
  143. //
  144. //    Worth noting in this utility is definition of the extractPictRecord. This is a 
  145. //    structure consisting of a CGrafPort structure followed by fields for a handle to 
  146. //    image data and an ImageDescription. This layout allows ExtractCompressData to open
  147. //    a CGrafPort using the embedded CGrafPort field, and set this as the current port. 
  148. //    Then, in the StdPix routine extractStdPix, the current port can be retrieved and 
  149. //    cast to a pointer to an extractPictRecord to get access to the other fields.
  150. //
  151.  
  152.  
  153. OSErr ExtractCompressData( PicHandle thePict, Handle *dataOut, ImageDescriptionHandle *idh )
  154. {
  155.     OSErr            err = noErr;
  156.     extractPictRecord     state;
  157.     CQDProcs             procs;
  158.     GrafPtr             savePort;
  159.     Rect                 bounds;
  160.  
  161.     if ( dataOut )
  162.         *dataOut = nil;
  163.     if ( idh )
  164.         *idh = nil;
  165.  
  166.     GetPort( &savePort );
  167.     state.tempPort = CreateNewPort();
  168.  
  169.     SetStdCProcs( &procs );
  170.     procs.newProc1 = (UniversalProcPtr)NewStdPixUPP(extractStdPix);
  171.     SetPortGrafProcs(state.tempPort, &procs);
  172.  
  173.     state.data = nil;
  174.     state.idh = nil;
  175.  
  176.     MacSetPort( (GrafPtr)state.tempPort );
  177.     HidePen();
  178.  
  179.     bounds = (**thePict).picFrame;
  180.     DrawPicture(thePict, &bounds);    
  181.  
  182.     MacSetPort( savePort );
  183.  
  184.     DisposePort(state.tempPort);
  185.     DisposeStdPixUPP((StdPixUPP)procs.newProc1);
  186.     
  187.     *dataOut    = state.data;
  188.     *idh        = state.idh;
  189.  
  190.     return err;
  191. }
  192.  
  193.  
  194. pascal void extractStdPix( PixMap *src, Rect *srcRect, MatrixRecord *matrix, short mode, RgnHandle mask, PixMap *matte, Rect *matteRect, short flags )
  195. {
  196. #if TARGET_OS_MAC
  197. #pragma unused(srcRect,matrix,mode,mask,matte,matteRect,flags)
  198. #endif
  199.     extractPictRecord    *state;
  200.  
  201.     GetPort( (GrafPtr *)&state );
  202.  
  203.     if  ( state->idh == nil ) {
  204.         ImageDescriptionHandle    desc;
  205.         Ptr                     data;
  206.         long                    bufferSize;
  207.         OSErr                     err;
  208.         if ( (err=GetCompressedPixMapInfo(src, &desc, &data, &bufferSize, nil, nil)) == noErr ) {
  209.             state->idh = desc;
  210.             HandToHand( (Handle *)&state->idh );
  211.             PtrToHand( data, &state->data, bufferSize );
  212.         }
  213.     }
  214. }
  215.  
  216.  
  217. static ImageDescriptionHandle createImageDescription( CodecType cType, PixMapHandle pixmap )
  218. {
  219.     ImageDescriptionHandle    desc = nil;
  220.     
  221.     if ( ( desc = (ImageDescription **)NewHandleClear(sizeof(ImageDescription)) ) != nil ) {
  222.         ImageDescription     *dp = *desc;
  223.         Rect                bounds = (**pixmap).bounds;
  224.  
  225.         dp->idSize             = sizeof(ImageDescription);
  226.         dp->cType             = cType;    
  227.         dp->spatialQuality     = codecNormalQuality;
  228.         dp->width            = bounds.right - bounds.left;
  229.         dp->height             = bounds.bottom - bounds.top;
  230.         dp->hRes             = 72L << 16;
  231.         dp->vRes             = 72L << 16;
  232.         dp->dataSize         = ((**pixmap).rowBytes & 0x3fff) * dp->height;
  233.         dp->depth             = (**pixmap).pixelSize;
  234.         dp->clutID             = -1;
  235.         
  236.         if ( SetImageDescriptionCTable( desc, (**pixmap).pmTable ) ) {
  237.             DisposeHandle( (Handle) desc );
  238.             desc = nil;
  239.         }
  240.     }
  241.     return desc;
  242. }
  243.  
  244. pascal void noDitherBitsProc(BitMap *srcBits, Rect *srcRect, Rect *dstRect, short mode, RgnHandle maskRgn);
  245. pascal void noDitherBitsProc(BitMap *srcBits, Rect *srcRect, Rect *dstRect, short mode, RgnHandle maskRgn)
  246. {
  247.     mode &= ~ditherCopy;
  248.     StdBits(srcBits, srcRect, dstRect, mode, maskRgn);
  249. }
  250.  
  251. //    DrawPictureNoDither is used to draw a QuickDraw picture but to turn convert any
  252. //    use of ditherCopy graphics modes to graphics modes that don't use ditherCopy. It
  253. //    only performs this with the stdbits bottleneck routine. Since ditherCopy is simply
  254. //    ORed in with other graphics modes, the replaced bottleneck routine only needs to
  255. //    AND off the ditherCopy flag.
  256. void DrawPictureNoDither(PicHandle pic, const Rect *bounds)
  257. {        
  258.     CQDProcs procs;
  259.     GrafPtr savePort;
  260.     CQDProcsPtr saveProcs;
  261.  
  262.     GetPort(&savePort);
  263.     saveProcs = GetPortGrafProcs(savePort);
  264.  
  265.     SetStdCProcs( &procs );
  266.  
  267.     procs.bitsProc = NewQDBitsUPP(noDitherBitsProc);
  268.  
  269.     SetPortGrafProcs(savePort, &procs);
  270.  
  271.  
  272.     DrawPicture(pic, bounds);
  273.  
  274.     SetPortGrafProcs(savePort, saveProcs);
  275.  
  276.     DisposeQDBitsUPP((QDBitsUPP)procs.bitsProc);
  277. }
  278.  
  279.  
  280. //
  281. // The following is a routine that can be used to clean up the colors in a picture
  282. // before being compressed with the Animation compressor in 16-bits at codecNormal
  283. // quality. The QuickTime Animation compressor can operate in both a lossless and
  284. // lossy manner. This routine is meant to help when compressing in a lossy manner.
  285. //
  286. // By clean up, what's meant is the forcing of any colors that are sufficiently close
  287. // to white to colors that are not as close. Since the Animation compressor will
  288. // perform threshholding of the image's colors when codecNormal quality is specified,
  289. // without this preprocessing, colors very close to white can be mapped to white
  290. // in the compression. If white was chosen as the key color, pixels that are
  291. // close to white could possibly become transparent as well.
  292. //
  293. // While not used by other routines in this file, prepareFor16BitCompress is provided
  294. // as an example of how this might be done.
  295. //
  296. // Note that with codecLossless quality, there is no remapping of colors so this
  297. // step is unnecessary.
  298. //
  299.  
  300. #define kThreshold (255 - 16)
  301.  
  302. OSErr prepareFor16BitCompress(PicHandle *pic)
  303. {
  304.     OSErr err = noErr;
  305.     PicHandle newPicture = nil;
  306.     Rect r;
  307.     GWorldPtr gw = nil;
  308.     CGrafPtr savePort;
  309.     GDHandle saveGD;
  310.     short rowBytes;
  311.     Ptr baseAddr;
  312.     long w, h;
  313.     PixMapHandle pm;
  314.  
  315.     GetGWorld(&savePort, &saveGD);
  316.  
  317.     r = (***pic).picFrame;
  318.     MacOffsetRect(&r, (short)-r.left, (short)-r.top);
  319.  
  320.     err = NewGWorld(&gw, 32, &r, nil, nil, useTempMem);
  321.     if (err) {
  322.         err = NewGWorld(&gw, 32, &r, nil, nil, 0);
  323.         if (err) goto bail;
  324.     }
  325.  
  326.     pm = GetGWorldPixMap(gw);
  327.     LockPixels(pm);
  328.     SetGWorld(gw, nil);
  329.     EraseRect(&r);
  330.  
  331.     DrawPicture(*pic, &r);
  332.  
  333.     baseAddr = GetPixBaseAddr(pm);
  334.     rowBytes = (**pm).rowBytes & 0x3fff;
  335.     for (h=0; h<r.bottom; h++) {
  336.         long *pixelPtr = (long *)baseAddr;
  337.  
  338.         for (w=0; w<r.right; w++, pixelPtr++) {
  339.             UInt8 r, g, b, a;
  340.             long pixel = *pixelPtr;
  341.  
  342.             if ((pixel & 0x0ffffff) == 0x00ffffff)        // pure white
  343.                 continue;
  344.  
  345.             a = (pixel >> 24) & 0x0ff;
  346.             r = (pixel >> 16) & 0x0ff;
  347.             g = (pixel >>  8) & 0x0ff;
  348.             b = (pixel >>  0) & 0x0ff;
  349.             if ((r > kThreshold) && (g > kThreshold) && (b > kThreshold)) {
  350.                 r = g = b = kThreshold;
  351.                 *pixelPtr = (a << 24) | (kThreshold << 16) | (kThreshold << 8) | (kThreshold << 0);
  352.             }
  353.         }
  354.  
  355.         baseAddr += rowBytes;
  356.     }
  357.  
  358.     newPicture = OpenPicture(&r);
  359.     CopyBits((BitMap *)&pm, (BitMap *)&pm, &r, &r, ditherCopy, nil);
  360.  
  361.     ClosePicture();
  362.     UnlockPixels(pm);
  363.  
  364. bail:
  365.     if (gw)
  366.         DisposeGWorld(gw);
  367.  
  368.     if (err == noErr) {
  369.         if (newPicture) {
  370.             KillPicture(*pic);
  371.             *pic = newPicture;
  372.         }
  373.     }
  374.  
  375.     SetGWorld(savePort, saveGD);
  376.  
  377.     return err;
  378. }
  379.  
  380.  
  381. /*
  382.     ---------------- Callback based routines for compressing with hittesting and transparency ----------------
  383.  */
  384.  
  385. /*
  386.     RecompressWithTransparencyFromProc
  387.     
  388.     This is a routine either called indirectly through RecompressCompressedImageWithTransparency, 
  389.     RecompressPictureWithTransparency, or RecompressPictureFileWithTransparency or called directly.
  390.     It takes a callback procedure which is responsible for returning the dimensions of the
  391.     area of some type of drawable entity and for actually drawing that entity.
  392.     
  393.         includeHitTesting        TRUE if hit testing data should be added to the compressed data
  394.         keyColor                A RGBColor that should be used as the transparency color. Pass nil
  395.                                 if the image doesn't have transparent portions.
  396.         hitTestRegion            A RgnHandle specifying an area that is to be used as the hit test
  397.                                 area. If you pass this, you must also set includeHitTesting to TRUE.
  398.                                 This is optional as the callback procedure can perform drawing
  399.                                 itself of the hit test area which is often suitable when both the
  400.                                 image and hit test area were painted in a drawing program.
  401.         idh                        Returned ImageDescriptionHandle for the compressed image data
  402.         imageData                Returned Handle to the compressed image data
  403.  
  404.  */
  405. OSErr RecompressWithTransparencyFromProc( CompressDrawProc drawProc, void * drawProcRefcon, 
  406.                                                     Boolean includeHitTesting,
  407.                                                     RGBColor *keyColor, 
  408.                                                     RgnHandle hitTestRegion,
  409.                                                     ImageDescriptionHandle *idh, Handle * imageData )
  410. {
  411.     OSErr                         err = noErr;
  412.     Rect                        bounds;
  413.     CGrafPtr                    savePort;
  414.     GDHandle                    saveDevice;
  415.     GWorldPtr                    gwImage = nil;        // always used
  416.     GWorldPtr                    gwPrev = nil;        // used if compressing with transparency (via keycolor)
  417.     GWorldPtr                    gwMap = nil;        // used if compressing with hittesting data
  418.     ImageDescriptionHandle        desc = nil;            // resulting image description
  419.     ImageDescriptionHandle        gwMapDesc = nil;
  420.     ImageSequence                seq = 0;            // compress sequence
  421.     ImageSequenceDataSource        mapSource = 0L;
  422.     Ptr                            data = nil;
  423.     long                         dataSize;
  424.     UInt8                         similarity;
  425.     Boolean                        includeTransparency = false;
  426.     RGBColor                    saveBackColor;
  427.         
  428.     GetGWorld( &savePort, &saveDevice );
  429.     
  430.     if( !drawProc || !idh || !imageData ){
  431.         err = paramErr;
  432.         goto bail;
  433.     }
  434.     
  435.     // tell callback that it should initialize any storage it needs
  436.     err = drawProc( kRecoProcInitMsg, nil, nil, 0, drawProcRefcon );
  437.     if(err) goto bail;
  438.     
  439.     // determine bounds to use for compression
  440.     err = drawProc( kRecoProcGetBoundsMsg, &bounds, nil, 0, drawProcRefcon );
  441.     if(err) goto bail;
  442.     
  443.     err = QTNewGWorld(&gwImage, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  444.     if(err) goto bail;
  445.  
  446.     if( keyColor ) {
  447.         includeTransparency = true;
  448.     }
  449.     
  450.     // Include hit testing? If so, we need a previous buffer and an 8-bit GWorld for the mask data
  451.     if( includeHitTesting ) {
  452.         err = QTNewGWorld(&gwPrev, kCompressDepth, &bounds, nil, nil, kICMTempThenAppMemory);
  453.         if(err) goto bail;
  454.  
  455.         err = QTNewGWorld(&gwMap, 8, &bounds, nil, nil, kICMTempThenAppMemory);
  456.         if(err) goto bail;
  457.     }
  458.     
  459.     LockPixels( GetGWorldPixMap(gwImage) );
  460.     
  461.     if( gwPrev )
  462.         LockPixels( GetGWorldPixMap(gwPrev) );
  463.     
  464.     if( gwMap )
  465.         LockPixels( GetGWorldPixMap(gwMap) );
  466.     
  467.     if(gwPrev) {
  468.         SetGWorld( gwPrev, nil );
  469.         ClipRect( &bounds );
  470.         
  471.         GetBackColor( &saveBackColor );
  472.         if( keyColor )
  473.             RGBBackColor( keyColor );
  474.         
  475.             EraseRect( &bounds );
  476.             
  477.         RGBBackColor( &saveBackColor );
  478.     }
  479.     
  480.     if( gwMap ) {
  481.         SetGWorld( gwMap, nil );
  482.         
  483.         EraseRect( &bounds );            // paint background white
  484.  
  485.         err = drawProc( kRecoProcDrawMsg, &bounds, gwMap, kRecoProcHitTestingImageType, drawProcRefcon );
  486.         if(err) goto bail;
  487.         
  488.         if( hitTestRegion ) {
  489.             RGBColor blackRGB;
  490.             
  491.             blackRGB.red = blackRGB.green = blackRGB.blue = 0;
  492.             
  493.             RGBForeColor( &blackRGB );
  494.             MacPaintRgn( hitTestRegion );
  495.         }
  496.  
  497.         gwMapDesc = createImageDescription(kRawCodecType, GetGWorldPixMap(gwMap));
  498.         err = MemError();
  499.         if(err) goto bail;
  500.     }
  501.     
  502.     SetGWorld( gwImage, nil );
  503.     ClipRect( &bounds );
  504.     EraseRect( &bounds );
  505.     
  506.     desc = (ImageDescriptionHandle) NewHandle(sizeof(ImageDescription));
  507.  
  508.  
  509.     // NOTE: We pass codecLosslessQuality so that the key color if any is matched exactly. This avoids colors within
  510.     // some threshhold different from the key color being taken as equivalent to the key color. Alternatively, we
  511.     // could perform some threshhold processing on the source image's pixels and pass codecNormalQuality.
  512.     if( includeHitTesting ) {
  513.         // Allocate a compression sequence and add source data for hittest mask
  514.         err = CompressSequenceBegin(&seq, GetGWorldPixMap(gwPrev), nil, nil, nil, kCompressDepth, kAnimationCodecType, 
  515.                                             anyCodec, codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc);
  516.  
  517.         // with hit testing, we have to add a data source to hold the mask data
  518.         err = CDSequenceNewDataSource(seq, &mapSource, kRecoProcHitTestingImageType, 1, (Handle)gwMapDesc, nil, nil);
  519.         if (err) goto bail;
  520.  
  521.         err = CDSequenceSetSourceData(mapSource, GetPixBaseAddr(GetGWorldPixMap(gwMap)), (**gwMapDesc).dataSize);
  522.         if (err) goto bail;
  523.  
  524.         // What's the maximum size the compressed data could be--including hit-test data?
  525.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwPrev), &dataSize);
  526.     }
  527.     else
  528.     {    // not hit-testing so we only need the image buffer
  529.         err = CompressSequenceBegin( &seq, GetGWorldPixMap(gwImage), nil, &bounds, nil, kCompressDepth, kAnimationCodecType, 0, 
  530.                                     codecLosslessQuality, codecLosslessQuality, 2, nil, 0, desc );
  531.         if(err) goto bail;
  532.         
  533.         // What's the maximum size the compressed data could be?
  534.         err = GetCSequenceMaxCompressionSize(seq, GetGWorldPixMap(gwImage), &dataSize);
  535.     }
  536.     if (err) goto bail;
  537.     
  538.  
  539.     data = NewPtr( dataSize );
  540.     if(noErr != (err = MemError())) goto bail;
  541.     
  542.     if( includeHitTesting /* with or without transparency */ ) {
  543.         // With hittesting, we use two buffers. Actually we don't have to but do so to show how it can be
  544.         // done. Also, this code was based upon some older code that did.
  545.         
  546.         
  547.         // compress the GWorld painted with the keyColor exclusively
  548.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwPrev), nil, 0, data, &dataSize, &similarity, nil );
  549.         if ( err ) goto bail;
  550.  
  551.         err = SetCSequencePrev(seq, GetGWorldPixMap(gwPrev), nil);
  552.         if (err) goto bail;
  553.  
  554.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  555.         // areas it doesn't paint will be in the key color
  556.         SetGWorld( gwImage, nil );
  557.         
  558.         GetBackColor( &saveBackColor );
  559.         if( keyColor )
  560.             RGBBackColor( keyColor );
  561.             
  562.             EraseRect( &bounds );
  563.         
  564.         RGBBackColor( &saveBackColor );
  565.     
  566.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  567.         if(err) goto bail;
  568.  
  569.         // now compress the GWorld holding the image drawn on top of the keyColor
  570.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil);
  571.         if (err) goto bail;
  572.         
  573.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  574.         // Also, hit testing data is contained in the image data if it was specified.
  575.     }
  576.     else if( includeTransparency ) {
  577.         // For transparency case without hittesting, we get by with only using a single buffer so we special case the
  578.         // code here. This is also for clarity.
  579.     
  580.         // compress the GWorld painted with the keyColor exclusively
  581.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil );
  582.         if ( err ) goto bail;
  583.  
  584.         // draw the image into the GWorld over area painted with keyColor so that if picture is transparent already
  585.         // areas it doesn't paint will be in the key color
  586.         SetGWorld( gwImage, nil );
  587.         
  588.         GetBackColor( &saveBackColor );
  589.         if( keyColor )
  590.             RGBBackColor( keyColor );
  591.             
  592.             EraseRect( &bounds );
  593.         
  594.         RGBBackColor( &saveBackColor );
  595.     
  596.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  597.         if(err) goto bail;
  598.  
  599.         // now compress the GWorld holding the image drawn on top of the keyColor
  600.         err = CompressSequenceFrame(seq, GetGWorldPixMap(gwImage), nil, codecFlagUpdatePrevious, data, &dataSize, &similarity, nil);
  601.         if (err) goto bail;
  602.         
  603.         // At this point, data points to the image data for just the difference between the two (thus generating transparency) 
  604.         // Also, hit testing data is contained in the image data if it was specified.
  605.     }
  606.     else
  607.     {
  608.         SetGWorld( gwImage, nil );
  609.  
  610.         // draw the image into the GWorld
  611.         err = drawProc( kRecoProcDrawMsg, &bounds, gwImage, kRecoProcOriginalImageType, drawProcRefcon );
  612.         if(err) goto bail;
  613.  
  614.         // compress the GWorld containing the image painted on white
  615.         err = CompressSequenceFrame( seq, GetGWorldPixMap(gwImage), nil, 0, data, &dataSize, &similarity, nil );
  616.         if ( err ) goto bail;
  617.         
  618.         // At this point, data points to the image data for just the image, newly compressed. Also, hit testing data is contained
  619.         // in the image data if it was specified.
  620.     }
  621.     
  622.     CDSequenceEnd( seq );
  623.     seq = 0;
  624.     
  625.     // free the GWorlds and drop references so we have more memory for PtrToHand
  626.     if( gwImage )    DisposeGWorld( gwImage );
  627.     gwImage = nil;
  628.     if( gwMap )    DisposeGWorld( gwMap );
  629.     gwMap = nil;
  630.     if( gwPrev ) DisposeGWorld( gwPrev );
  631.     gwPrev = nil;
  632.     
  633.     err = PtrToHand( data, imageData, dataSize );
  634.     if ( err ) goto bail;
  635.     
  636.     *idh = desc;
  637.     desc = nil;                // forget about this name for ImageDescriptionHandle so dispose below doesn't catch it
  638.     
  639. bail:
  640.     // tell callback to dispose of anything it allocated. We pass 'err ' in portType if an error occurred
  641.     drawProc( kRecoProcDisposeMsg, nil, nil, err ? FOUR_CHAR_CODE('err ') : 0, drawProcRefcon );
  642.     
  643.     CDSequenceEnd( seq );
  644.     SetGWorld( savePort, saveDevice );
  645.     
  646.     if(gwImage)        DisposeGWorld( gwImage );
  647.     if(gwMap )        DisposeGWorld( gwMap );
  648.     if(gwPrev )        DisposeGWorld( gwPrev );
  649.     if(desc)         DisposeHandle((Handle) desc );
  650.     if(gwMapDesc)    DisposeHandle((Handle) gwMapDesc );
  651.     if(data)        DisposePtr( data );
  652.         
  653.     return err;
  654. }
  655.  
  656.  
  657. /*
  658.     myPictureCompressDrawProc
  659.     
  660.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickDraw Pictures.
  661.  */
  662.  
  663. static pascal OSErr myPictureCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  664. {
  665. #if TARGET_OS_MAC
  666. #pragma unused(drawingPort)
  667. #endif
  668.     OSErr err = noErr;
  669.     PictureCompressProcData * data = refcon;
  670.     Rect r;
  671.  
  672.     switch( message ) {
  673.         case kRecoProcInitMsg:
  674.             break;
  675.             
  676.         case kRecoProcDisposeMsg:
  677.             break;
  678.             
  679.         case kRecoProcGetBoundsMsg:
  680.             r = (**data->picture).picFrame;
  681.             
  682.             r.left = EndianS16_BtoN(r.left);
  683.             r.top = EndianS16_BtoN(r.top);
  684.             r.bottom = EndianS16_BtoN(r.bottom);
  685.             r.right = EndianS16_BtoN(r.right);
  686.             
  687.             MacOffsetRect(&r, (short)-r.left, (short)-r.top );
  688.             
  689.             *bounds = r;
  690.             break;
  691.             
  692.         case kRecoProcDrawMsg:
  693.             r = (**data->picture).picFrame;
  694.             
  695.             r.left = EndianS16_BtoN(r.left);
  696.             r.top = EndianS16_BtoN(r.top);
  697.             r.bottom = EndianS16_BtoN(r.bottom);
  698.             r.right = EndianS16_BtoN(r.right);
  699.  
  700.             MacOffsetRect( &r, (short)-r.left, (short)-r.top );
  701.  
  702.             if( kRecoProcOriginalImageType == drawingImageType )
  703.                 DrawPictureNoDither( data->picture, &r );
  704.             break;
  705.         default:
  706.             err = -1;
  707.     }
  708.  
  709.     return err;
  710. }    
  711.     
  712.  
  713. /*
  714.     myImageCompressDrawProc
  715.     
  716.     Helper routine to be used with RecompressWithTransparencyFromProc to compress QuickTime compressed image data.
  717.  */
  718. static pascal OSErr myImageCompressDrawProc( short message, Rect * bounds, GWorldPtr drawingPort, OSType drawingImageType, void * refcon )
  719. {
  720. #if TARGET_OS_MAC
  721. #pragma unused(drawingImageType)
  722. #endif
  723.  
  724.     OSErr err = noErr;
  725.     CompressedImageCompressProcData * data = refcon;
  726.     Rect r;
  727.     
  728.     switch( message ) {
  729.     case kRecoProcInitMsg:
  730.         break;
  731.     case kRecoProcDisposeMsg:
  732.         break;
  733.     case kRecoProcGetBoundsMsg:
  734.         r.left = r.top = 0;
  735.         r.right = (**data->imageDesc).width;
  736.         r.bottom = (**data->imageDesc).height;
  737.         
  738.         *bounds = r;
  739.         break;
  740.     case kRecoProcDrawMsg:
  741.         {
  742.             SignedByte saveState;
  743.             
  744.             r.left = r.top = 0;
  745.             r.right = (**data->imageDesc).width;
  746.             r.bottom = (**data->imageDesc).height;
  747.             
  748.             saveState = HGetState( data->imageData );
  749.             HLockHi( data->imageData );
  750.             
  751.             if( kRecoProcOriginalImageType == drawingImageType )
  752.                 err = DecompressImage( *data->imageData, data->imageDesc, GetGWorldPixMap(drawingPort), &r, &r, srcCopy, nil );
  753.             
  754.             HSetState( data->imageData, saveState );
  755.         }
  756.         break;
  757.     default:
  758.         err = -1;
  759.     }
  760.  
  761.     return err;
  762. }    
  763.  
  764.  
  765.  
  766. /*
  767.     RecompressCompressedImageWithTransparency
  768.     
  769.     Given an ImageDescriptionHandle and a handle to image data, generate new RLE compressed data
  770.     with optional hitTesting and transparency.
  771.  */
  772. OSErr RecompressCompressedImageWithTransparency( ImageDescriptionHandle originalDesc, Handle originalImageData,
  773.                                         RGBColor *keyColor, 
  774.                                         RgnHandle hitTestRegion,
  775.                                         ImageDescriptionHandle *idh, Handle * imageData )
  776. {
  777.     OSErr err = noErr;
  778.     CompressedImageCompressProcData params;
  779.     
  780.     params.imageDesc = originalDesc;
  781.     params.imageData = originalImageData;
  782.     
  783.     err = RecompressWithTransparencyFromProc( myImageCompressDrawProc, ¶ms, 
  784.                                         (Boolean)(hitTestRegion != nil), 
  785.                                         keyColor, 
  786.                                         hitTestRegion, 
  787.                                         idh, imageData );
  788.     
  789.     return err;
  790. }
  791.  
  792. /*
  793.     RecompressPictureWithTransparency
  794.     
  795.     Given a QuickDraw PicHandle, generate new RLE compressed data with optional hitTesting and transparency.
  796.  */
  797. OSErr RecompressPictureWithTransparency( PicHandle originalPicture,
  798.                                         RGBColor *keyColor, 
  799.                                         RgnHandle hitTestRegion,
  800.                                         ImageDescriptionHandle *idh, Handle * imageData )
  801. {
  802.     OSErr err = noErr;
  803.     PictureCompressProcData params;
  804.     
  805.     params.picture = originalPicture;
  806.     
  807.     err = RecompressWithTransparencyFromProc( myPictureCompressDrawProc,
  808.                                             ¶ms, 
  809.                                             (Boolean)(hitTestRegion != nil), 
  810.                                             keyColor, 
  811.                                             hitTestRegion, 
  812.                                             idh,
  813.                                             imageData );
  814.     
  815.     return err;
  816. }
  817.  
  818. /*
  819.     RecompressPictureFileWithTransparency
  820.     
  821.     Given a QuickDraw PICT file, generate new RLE compressed data with optional hitTesting and transparency.
  822.     This function uses GetCompressedImageFromPicture to do the actual work on the PicHandle retrieved from
  823.     the PICT file.
  824.  */
  825. OSErr RecompressPictureFileWithTransparency( FSSpec * spec, 
  826.                                         RGBColor *keyColor, 
  827.                                         RgnHandle hitTestRegion,
  828.                                         ImageDescriptionHandle *idh, Handle * imageData )
  829. {
  830.     OSErr         err = noErr;
  831.     short        sourceRefNum = 0;
  832.     PicHandle    picture = nil;
  833.     long        eof;
  834.     long        countBytes;
  835.     
  836.     *idh = nil;
  837.     *imageData = nil;    
  838.     
  839.     BailOSErr(FSpOpenDF( spec, fsRdPerm, &sourceRefNum ));
  840.     
  841.     BailOSErr(GetEOF( sourceRefNum, &eof ));
  842.     eof -= 512;
  843.     
  844.     BailOSErr(SetFPos( sourceRefNum, fsFromStart, 512 ));
  845.             
  846.     picture = (PicHandle) NewHandle(eof);
  847.     err = MemError();
  848.     BailOSErr(err);
  849.  
  850.     countBytes = eof;
  851.     HLock((Handle) picture);
  852.     BailOSErr( FSRead( sourceRefNum, &countBytes, *picture) );
  853.     HUnlock((Handle) picture);
  854.     
  855.     BailOSErr( RecompressPictureWithTransparency( picture,  keyColor, hitTestRegion,
  856.                                 idh, imageData ));
  857.                                 
  858. bail:
  859.     if ( picture )            DisposeHandle((Handle) picture );
  860.     if ( sourceRefNum )        FSClose( sourceRefNum );
  861.         
  862.     return err;
  863. }
  864.  
  865. #endif
  866.  
  867.